package com.firewolf.rbac.service.impl;

import com.firewolf.rbac.mapper.UserMapper;
import com.firewolf.rbac.mapper.UserRoleMapper;
import com.firewolf.rbac.params.UserParam;
import com.firewolf.rbac.pojo.User;
import com.firewolf.rbac.pojo.UserRole;
import com.firewolf.rbac.pojo.UserRoleExample;
import com.firewolf.rbac.service.UserService;
import com.firewolf.rbac.vo.PageVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/2/28
 **/
@Service
public class UserServieImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public PageVO<User> findList(UserParam userParam) {

        PageHelper.startPage(userParam.getPageNum(), userParam.getPageSize());

        List<User> userList = userMapper.findByParams(userParam);

        PageInfo<User> pageInfo = new PageInfo<>(userList);

        return new PageVO<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public void saveUser(User user) {
        if (user.getId() == null) {
            user.setCreateTime(new Date());
            user.setDelFlag((byte) 0);
            user.setStatus((byte) 1);
            userMapper.insert(user);
        } else {
            userMapper.updateByPrimaryKeySelective(user);
            //更新，需要先删除关联的角色
            UserRoleExample userRoleExample = new UserRoleExample();
            userRoleExample.createCriteria().andUserIdEqualTo(user.getId());
            userRoleMapper.deleteByExample(userRoleExample);
        }

        String roles = user.getRoleids();
        if (roles != null) {
            String[] split = roles.split(",");
            for (String s : split) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(Long.parseLong(s));
                userRole.setUserId(user.getId());
                userRole.setCreateTime(new Date());
//                userRole.setCreateBy("admin"); //当前用户
//                userRole.setLastUpdateBy("admin");
                userRole.setLastUpdateTime(new Date());
                userRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectByExample(null);
    }
}
